package com.mall.gateway.service;

import com.mall.common.entity.gateway.GatewayLog;
import com.mall.common.mq.RocketMqUtil;
import com.mall.common.config.YamlPropertySourceFactory;
import com.mall.system.feign.LogServiceFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;

/**
 * 网关日志服务
 */
@Slf4j
@Service
@PropertySource(value = {"classpath:rocketmq.yml"}, factory = YamlPropertySourceFactory.class)
public class GatewayLogService {
    
    @Autowired
    private LogServiceFeignClient logServiceFeignClient;
    
    @Value("${rocketmq.name-server:localhost:9876}")
    private String nameServer;
    
    @Value("${rocketmq.producer.gateway-log-group:mall-gateway-log-producer}")
    private String producerGroup;
    
    @Value("${rocketmq.producer.gateway-log-topic:mall_gateway_log_queue}")
    private String gatewayLogTopic;
    
    @Value("${rocketmq.producer.gateway-log-tag:mall_gateway_log_tag}")
    private String gatewayLogTag;
    
    private RocketMqUtil rocketMqUtil;
    
    @PostConstruct
    public void init() {
        try {
            rocketMqUtil = new RocketMqUtil(nameServer, producerGroup);
            rocketMqUtil.initProducer();
            log.info("网关日志RocketMQ生产者初始化成功");
        } catch (Exception e) {
            log.error("初始化网关日志RocketMQ生产者失败: ", e);
        }
    }
    
    /**
     * 异步保存网关日志到系统服务
     * 
     * @param gatewayLog 网关日志
     */
    @Async
    public void saveLog(GatewayLog gatewayLog) {
        try {
            // 调用system服务的API保存日志
            com.mall.common.result.Result<Boolean> result = logServiceFeignClient.saveGatewayLog(gatewayLog);
            if (result.getCode() == 200 && result.getData() != null && result.getData()) {
                log.info("保存网关日志到系统服务成功: {}", gatewayLog.getId());
            } else {
                log.error("保存网关日志到系统服务失败: {}，错误信息: {}", gatewayLog.getId(), result.getMessage());
                // 保存失败，发送到消息队列
                sendLogToMq(gatewayLog);
            }
        } catch (Exception e) {
            log.error("保存网关日志到系统服务异常: ", e);
            // 保存失败，发送到消息队列
            // 将异常堆栈信息设置到responseData字段中
            gatewayLog.setResponseData(com.mall.common.util.ExceptionUtil.getStackTraceAsString(e));
            gatewayLog.setHttpStatus(500);
            gatewayLog.setResponseTime(LocalDateTime.now());
            sendLogToMq(gatewayLog);
        }
    }
    
    /**
     * 将日志发送到消息队列
     * 
     * @param gatewayLog 网关日志
     */
    private void sendLogToMq(GatewayLog gatewayLog) {
        if (rocketMqUtil != null) {
            try {
                String logJson = com.alibaba.fastjson.JSON.toJSONString(gatewayLog);
                rocketMqUtil.sendOnewayMessage(gatewayLogTopic, gatewayLogTag, logJson);
                log.info("网关日志已发送到消息队列: {}", gatewayLog.getId());
            } catch (Exception e) {
                log.error("发送网关日志到消息队列失败: ", e);
            }
        } else {
            log.warn("RocketMQ未初始化，无法发送日志到消息队列");
        }
    }
    
    /**
     * 销毁资源
     */
    public void destroy() {
        if (rocketMqUtil != null) {
            rocketMqUtil.shutdown();
        }
    }
}